package com.xqls.biz.impl;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xqls.bean.LoginBean;
import com.xqls.biz.LoginBiz;
import com.xqls.dal.model.Login;
import com.xqls.service.LoginService;
import com.xqls.util.CommonResult;
import com.xqls.util.ObjectUtil;

@Service
public class LoginBizImpl implements LoginBiz {
	private static Logger logger=Logger.getLogger(LoginBiz.class);
	
	@Autowired private LoginService loginService;
	
	@Override
	public List<Login> getLoginByMap(Map<String, Object> map) {
		List<Login> loginList=null;
		try {
			loginList=this.loginService.getLoginByMap(map);
		} catch (Exception e) {	
			logger.error("查询账户角色权限异常", e);
		}
		return loginList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LoginBean> getLoginBeanByMap(Map<String, Object> map) {
		List<LoginBean> loginList=null;
		try {
			loginList=ObjectUtil.transferList(this.loginService.getLoginByMap(map), LoginBean.class);
		} catch (Exception e) {	
			logger.error("查询账户角色权限异常", e);
		}
		return loginList;
	}
	
	@Override
	public void loginOut() {
		Subject subject = SecurityUtils.getSubject();
		if(subject!=null)
		{
			if (subject.isAuthenticated()) {
				subject.logout();
			}
		}
	}

	@Override
	public CommonResult doLogin(String userName, String password) {
		CommonResult commonResult=new CommonResult();
		Subject subject = SecurityUtils.getSubject();
		try {
			if (!subject.isAuthenticated()) {
				AuthenticationToken token = new UsernamePasswordToken(userName, password);
				subject.login(token);
			}
			commonResult.setIsSuccess(true);
		} catch (Exception e) {
			logger.error("查询账户异常", e);
			commonResult.setResultMsg("密码错误！");
		}
		return commonResult;
	}
}
